package com.ai.service.user.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.ai.common.model.Result;
import com.ai.common.model.pan.SizeVO;
import com.ai.common.utils.net.http.PanClient;
import com.ai.model.edu.user.PicResponse;
import com.ai.service.user.PicRoomService;

@Service("picRoomService")
public class PicRoomServiceImpl implements PicRoomService {
	@Value("${panUpload}")
	private String panUpload;
	@Value("${staticDomain}")
	private String staticDomain;

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public PicResponse handlSinglePicForProduct(MultipartFile uploadFile) {
		PicResponse picResponse = new PicResponse();
		String fileNamePatternStr = "";
		long maxFileSize  = (long) (10 * (2 << 19));
		List<SizeVO> list = new ArrayList<SizeVO>();
		list.add(new SizeVO(640,400));
		Result result = uploadIdPhoto(uploadFile,fileNamePatternStr,maxFileSize,false,list);
		if(!result.isSuccess()){
			picResponse.setErrorMsg(result.getMessage());
			return picResponse;
		}else{
		    String path = String.valueOf(result.getAttribute("url"));
		    //path += "_640x400.jpg";
			//picResponse.setUrl(staticDomain+path);
		    picResponse.setUrl(path);
		}
		return picResponse;
	}

	public Result uploadIdPhoto(MultipartFile uploadFile,String fileNamePatternStr,long maxFileSize,boolean addAttname,List<SizeVO> list){
        Result result = new Result(true,"");
        String uploadFilePath = System.getProperty("java.io.tmpdir");
        if (uploadFile == null ||
                uploadFile.getOriginalFilename() == null || "".equalsIgnoreCase(uploadFile.getOriginalFilename())) {
            result.setStateAndSuccess(-3, false, "上传文件为空");
        } else if (uploadFile.getSize() > maxFileSize) {
            result.setStateAndSuccess(-5, false, "上传文件超过指定大小");
        } else {
            String fileName = uploadFile.getOriginalFilename();
            if (StringUtils.isNotBlank(fileNamePatternStr)) {
                if (!Pattern.compile(fileNamePatternStr).matcher(fileName.toLowerCase()).matches()) {
                    result.setStateAndSuccess(-4, false, "文件类型不对");
                }
            }
            if (result.isSuccess()) {
            	uploadFilePath = this.getClass().getClassLoader().getResource("../../upload/images").getPath();
                File file = getFile(uploadFile,uploadFilePath);
                //String path = PanClient.sendFile(panUpload, file, "",list);
                //file.delete();
                String path = file.getName();
                if (StringUtils.isEmpty(path)) {
                    result.setStateAndSuccess(-8, false, "上传失败");
                } else {
                    path = addAttname ? path + "?attname="+ fileName : path;
                    result.addAttribute("url", path);
                }
            }
        }
        return result;
    }
	
	private File getFile(MultipartFile imgFile, String uploadImagePath) {
	    String fileName = imgFile.getOriginalFilename();
        String ext = FilenameUtils.getExtension(fileName).toLowerCase();
        StringBuilder  newFileName = new StringBuilder(UUID.randomUUID().toString());
        newFileName = newFileName.append(RandomStringUtils.randomAlphanumeric(1));
        newFileName.append('.').append(ext);
	    File file = this.creatFolder(uploadImagePath, newFileName.toString());
		try {
			FileUtils.copyInputStreamToFile(imgFile.getInputStream(), file);
		} catch (IOException e) {
			logger.error("UploadFileServerImpl get File is error ", e);
		}
		return file;
	}

	private File creatFolder(String uploadImagePath, String fileName) {
		File file = null;
		File firstFolder = new File(uploadImagePath); // 一级文件夹
		if (!firstFolder.exists()) { // 如果一级文件夹存在，则检测二级文件夹
			firstFolder.mkdirs();
		}
		file = new File(firstFolder, fileName);
		return file;
	}
}
